﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HR60_PanelSoft.Model;

namespace HR60_PanelSoft.Service
{
	public class PanelService : CommonService
	{
		// 保存
		public static void save(Panel source, Panel dto)
		{
			source.name = dto.name;
			source.index = dto.index;
			source.style = dto.style;
			source.eplusType = dto.eplusType;
		}
		
		// 添加
		public static void append(Panel panel, HR60_PanelSoft.Model.Net net)
		{
			net.panels.Add (panel);
		}
		public static Panel append(PanelType type, HR60_PanelSoft.Model.Net net)
		{
			Panel panel = PanelTypeService.getPanelCreator().create(type);
			panel.index = PanelService.newPanelId(net);
			net.panels.Add(panel);
			return panel;
		}

		// 删除
		public static void remove(Panel panel)
		{
			// 卸载负载关系
			foreach (Pin pin in panel.loadPins)
			{
				if (pin.isMainPin) 
				{
					// 卸载场景关系
					resetSceneByRemovePin (pin);

					pin.getConnectedDevice().connectedPins.Clear ();
					pin.isMainPin = false;
				}
				pin.connectedDevice = null;
			}

			// 卸载485线路
			if (panel.type.hasM485Model && panel.m485Pin.connectedDevice != null)
			{
				// 卸载场景关系
				resetSceneByRemovePin (panel.m485Pin);

				panel.m485Pin.getConnectedDevice().connectedPins.Clear ();
				panel.m485Pin.connectedDevice = null;
				panel.m485Pin.isMainPin = false;
			}

			// 删除
			foreach (HR60_PanelSoft.Model.Net net in proj.nets) 
			{
				if (net.panels.Contains (panel))
					net.panels.Remove (panel);
			}
		}

		// 卸载场景关系
		private static void resetSceneByRemovePin(Pin pin)
		{
			foreach (Scene scene in proj.scenes)
			{
				foreach(SceneEvent evet in scene.events)
				{
					if (evet.device == pin.connectedDevice)
						scene.events.Remove (evet);
				}
			}
		}

		public static int newPanelId(HR60_PanelSoft.Model.Net net)
		{
			for (int id = 1; id < 512; id++)
			{
				bool findFlag = false;
				for (int i = 0; i < net.panels.Count; i++)
				{
					if (id == net.panels[i].index)
					{
						findFlag = true;
						break;
					}
				}
				if (!findFlag) return id;
			}
			return -1;
		}
	}
}
